package com.zkadmin.service.impl;

import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import com.mysema.query.types.Predicate;
import com.zkadmin.entity.SysRole;
import com.zkadmin.entity.SysUser;
import com.zkadmin.repository.SysMenuRepository;
import com.zkadmin.repository.SysResourceRepository;
import com.zkadmin.repository.SysRoleRepository;
import com.zkadmin.service.SysRoleService;

@Service("sysRoleService")
public class SysRoleServiceImpl implements SysRoleService {
	@Autowired
	private SysRoleRepository repository;

	@Autowired
	private SysMenuRepository menuRepository;

	@Autowired
	private SysResourceRepository resourceRepository;

	@Override
	public SysRole save(SysRole role) {
		return repository.save(role);
	}

	@Override
	public Page<SysRole> paging(Predicate predicate, Pageable pageable) {
		return repository.findAll(predicate, pageable);
	}

	@Override
	public void delete(Long roleId) {
		SysRole role = repository.findOne(roleId);
		if (role != null) {
			Set<SysUser> users = role.getUsers();
			for (SysUser user : users) {
				user.removeRole(role);
			}
			repository.delete(role);
		}
	}

	@Override
	public void correlationResources(Long roleId, Set<Long> resourceIds) {
		SysRole role = findById(roleId);
		if (role != null) {
			role.getResources().clear();
			for (Long resourceId : resourceIds) {
				role.addResource(resourceRepository.findOne(resourceId));
			}
			repository.save(role);
		}
	}

	@Override
	public void correlationMenus(Long roleId, Set<Long> menuIds) {
		SysRole role = findById(roleId);
		if (role != null) {
			role.getMenus().clear();
			for (Long menuId : menuIds) {
				role.addMenu(menuRepository.findOne(menuId));
			}
			repository.save(role);
		}
	}

	@Override
	public SysRole findById(Long id) {
		return repository.findOne(id);
	}

	@Override
	public SysRole findByName(String name) {
		return repository.findByName(name);
	}

	@Override
	public SysRole findByRole(String role) {
		return repository.findByRole(role);
	}
}
